package sort;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @Author leecho
 * @Date: 2021/10/19 12:24
 * @Version 1.0
 */

public class ShellSort {
    public static void main(String[] args) {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");
        System.out.println(df.format(new Date()));

        System.out.println();
        ShellSort shellSort = new ShellSort();
//        int[] arr = {4,32,1223,4124,2,13,122};
        int[] ints = new int[80000];
        for (int i = 0; i < 80000; i++) {
            ints[i] = (int) (Math.random()*80000);
        }

        shellSort.shellSort2(ints);
//        shellSort.insertSort(ints);
        System.out.println(df.format(new Date()));
//        System.out.println(Arrays.toString(ints));
    }
    
    /*
    * 思路
    * - 就行在插入排序前，先进行排序，但并不是最后的结果
    * - 减少插入排序比较的时间
    * */
    public void shellSort(int[] arr){
        int temp = 0;
        for (int gap = arr.length / 2; gap > 0 ; gap /= 2) {
            for (int i = 0; i < gap; i++) {
                if (arr[i] > arr[i+gap]){
                    temp = arr[i];
                    arr[i] = arr[i+gap];
                    arr[i+gap] = temp;
                }
            }
        }
        insertSort(arr);
    }

    public void insertSort(int[] arr){
        for (int i = 1; i < arr.length; i++) {
            int temp = arr[i];
            int index = i-1;
            while (index >= 0 && temp < arr[index] ){
                arr[index+1] = arr[index];
                index--;
            }
            arr[index+1] = temp;
        }
    }

    public void shellSort2(int[] arr){
        int temp = 0;
        int j = 0;
        for (int gap = arr.length / 2; gap > 0 ; gap /= 2) {
            for (int i = 0; i < gap; i++) {
                 j = i;
                temp = arr[i];
                while (j + gap < arr.length && temp > arr[j+gap]){
                    arr[j] = arr[j+gap];
                    j += gap;
                }
                arr[j] = temp;
            }
        }
        insertSort(arr);
    }
}
